/**
 * gen package definition for develop mode
 * @author yiminghe@gmail.com
 */
/*jshint quotmark:false, camelcase:false*/
var cwd = normalizeSlash(process.cwd());
var path = require('path');
var startDir = normalizeSlash(path.resolve(cwd, 'src') + '/');
var saveTo = startDir + 'package.js';
var base = '/kissy/src/';
var fs = require('fs');
var suffixLen = '/src'.length;
var esprima = require('esprima');
var escodegen = require('escodegen');
//noinspection JSUnresolvedVariable
var currentDir = __dirname;

function normalizeSlash(str) {
    return str.replace(/\\/g, '/');
}

function collectSrcDir(dir, allSrc) {
    var files = fs.readdirSync(dir);
    files.forEach(function (f) {
        var c = dir + f;
        var state = fs.statSync(c);
        if (state.isDirectory()) {
            if (f === 'src') {
                allSrc.push(c);
            } else if (f !== 'coverage') {
                collectSrcDir(c + '/', allSrc);
            }
        }
    });
}

function beautify(str) {
    return escodegen.generate(esprima.parse(str));
}

var allSrc = [];

collectSrcDir(startDir, allSrc);

var mod = {};

allSrc.forEach(function (v) {
    v = '/kissy/' + v.replace(cwd + '/', '');
    var name = v.substring(base.length, v.length - suffixLen);
    name = name.replace(/sub-modules\//g, '');
    mod[name] = {
        base: v + '/' + path.basename(name)
    };
});

// write server config

var serverConfig = fs.readFileSync(currentDir + '/server.json', {
    encoding: 'utf-8'
});

var header = [
    "/**" ,
    "    Generated By gen-package." ,
    "    For dev mode only!" ,
    "*/" ,
    "/*jshint quotmark:false, unused:false*/"
].join('\n');

var code = ["var SERVER_CONFIG=" + serverConfig + ";",
    "KISSY.config('tag',+ new Date());" ,
    "var loc = location;",
    "if (loc.search.indexOf('build') === -1 && loc.search.indexOf('min') === -1) {",
    "KISSY.DEV_MODE = 1;",
    "KISSY.config('packages', " ,
    JSON.stringify(mod),
    ');}'].join('\n');

fs.writeFileSync(saveTo, beautify([header, code].join('\n')));

console.log('saved to: ' + saveTo);







